package com.niit.musicserve.Intercepoter;

import com.niit.musicserve.annotation.RequireRole;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class RoleInterceptor implements HandlerInterceptor {
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		
		//判断当前请求是否为方法请求
		if(!(handler instanceof HandlerMethod)){
			return true;
		}
		
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		RequireRole requireRole = handlerMethod.getMethodAnnotation(RequireRole.class);
		
		//如果没有@RequireRole注解，则不需要检查
		if(requireRole == null){
			requireRole = handlerMethod.getBeanType().getAnnotation(RequireRole.class);
			if(requireRole == null){
				return true;
			}
		}
		
		//获取用户类型
		Claims claims = (Claims)request.getAttribute("claims");
		if(claims == null){
			response.setStatus(401);
			response.setContentType("application/json;charset=UTF-8");
			response.getWriter().write("{\"code\":401,\"message\":\"未认证用户\"}");
			return false;
		}
	        String userType = (String)claims.get("type");
		if (userType == null){
			response.setStatus(402);
			response.setContentType("application/json;charset=UTF-8");
			response.getWriter().write("{\"code\":401,\"message\":\"用户类型未知\"}");
			return false;
		}
		
		String[] requireRoles = requireRole.value();
		for (String role : requireRoles){
			if (userType.equals(role)){
				return true;
			}
		}
		
		response.setStatus(403);
		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().write("{\"code\":403,\"message\":\"用户无权限\"}");
		return false;
	}
}
